import React from 'react';
import 'react-chat-elements/dist/main.css';
import { WingBlank } from 'antd-mobile';
import { Helmet } from "react-helmet";
import _ from 'lodash';
import moment from 'moment';
import styles from './ChatMessage.less';
import MessageItem from './MessageItem';
import InputBar from './InputBar';
import { SystemMessage } from 'react-chat-elements';

class ChatMessage extends React.Component {
  constructor(props) {
    super(props);
    const state = {
      messages: [],
      sender: {},
      target: {},
      imOK: false,
      unreadTimer: null,
    };
    this.state = state;
  }

  componentDidMount() {
    this.setupUnreadTimer();
    this.scrollToBottom();
  }

  componentDidUpdate() {
    this.scrollToBottom();
  }

  scrollToBottom = () => {
    setTimeout(() => {
      if (this.messageList) {
        this.messageList.scrollTop = this.messageList.scrollHeight;
      }
    }, 500);
  }

  onSendMessage = (data) => {
    if (data && data.type && data.value) {
      this.props.onSendMessage(data.type, data.value);
    }
  }

  componentWillUnmount() {
    clearInterval(this.state.unreadTimer);
  }

  setupUnreadTimer() {
    const { messages, onReadMessage, target } = this.props;
    if (messages && messages.length) {
      const timer = setTimeout(() => {
        const messageIds = [];
        _.forEach(messages, (message) => {
          if (message.unread && target.userId == message.senderId) {
            messageIds.push(message.messageId);
          }
        });
        if (messageIds.length && onReadMessage) {
          onReadMessage(messageIds);
        }
      }, 2500);
      this.setState({
        unreadTimer: timer,
      });
    }
  }

  renderMessageList = () => {
    const { senderType, sender: { userId: senderId }, target: { userId: targetId }, messages } = this.props;
    const items = [];
    let lastTime, currentTime;
    const now = moment();
    const TODAY = now.clone().startOf('day');
    const YESTERDAY = now.clone().subtract(1, 'days').startOf('day');
    _.forEach(messages, (message, index) => {
      currentTime = message.sendTime;
      let format = 'YYYY年M月D日 HH:mm';
      if (moment(currentTime).isSame(TODAY, 'd')) {
        format = '今天 HH:mm';
      } else if (moment(currentTime).isSame(YESTERDAY, 'd')) {
        format = '昨天 HH:mm';
      }

      if (index === 0) {
        items.push(<SystemMessage
          key={`SystemMessage${index}`}
          text={moment(message.sendTime).format(format)}
        />);
      } else {
        if (moment(currentTime).diff(moment(lastTime), 'hours') >= 2) {
          items.push(<SystemMessage
            key={`SystemMessage${index}`}
            text={moment(message.sendTime).format(format)}
          />);
        }
      }
      items.push(<MessageItem
        time={moment(message.sendTime).format('MM-DD HH:mm')}
        key={`MessageItem${index}`}
        position={message.senderId === targetId ? 'left' : 'right'}
        content={message.content}
        avatar={(message.senderId === senderId && senderType === 'vip') || (message.senderId === targetId && senderType === 'saleman') ? 'http://wx.hy-bang.com/im/vip_avatar.png' : 'http://wx.hy-bang.com/im/saleman_avatar.png'}
      />);
      lastTime = message.sendTime;
    });
    return (<div>
      { items }
      <MessageItem key={'bottomMessage1'} />
      <MessageItem key={'bottomMessage2'} />
      <MessageItem key={'bottomMessage3'} />
    </div>);
  }

  render() {
    return (<div className={styles.chatMessage}>
      <Helmet>
        <style>{'html, body, #root { height: 100%; overflow: hidden; }'}</style>
        <style>{'#root > div { height: 100%; padding-bottom: 0; }'}</style>
        <meta content="yes" name="apple-mobile-web-app-capable" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      </Helmet>
      <div ref={(el) => { this.messageList = el; }} className={styles.messageContainer}>
        <WingBlank>
          {this.renderMessageList()}
        </WingBlank>
      </div>
      <div className={styles.inputBarContainer}>
        <InputBar
          onSubmit={this.onSendMessage}
        />
      </div>
    </div>);
  }
}

ChatMessage.propTypes = {
  onReadMessage: React.PropTypes.func,
  onSendMessage: React.PropTypes.func,
  senderType: React.PropTypes.oneOf(['vip', 'saleman']),
  sender: React.PropTypes.object,
  target: React.PropTypes.object,
  messages: React.PropTypes.array,
};

ChatMessage.defaultProps = {
  senderType: 'vip',
};

export default ChatMessage;
